package android.magical;

import java.util.Calendar;

import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.database.sqlite.SQLiteException;
import android.magical.MainActivity.MyAdapter;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

public class AddEventFragment extends Fragment implements OnClickListener, OnDateSetListener, OnTimeSetListener{
	private final String TAG = "DummyFragment";

	public static Calendar currentDate;
	private DatabaseControl dbControl;
	
	private int day = 0;
	private int month = 0;
	private int thisYear = 0;
	private int hour = 0;
	private int minutes = 0;
	private String currentDateString;
	private String currentTimeString;
	private Editable message;
	
	protected TextView viewDate;
	protected TextView viewTime;
	protected ImageButton changeDate;
	protected ImageButton changeTime;
	protected Button save;
	protected EditText messageText;
	
	static final String DATE_DIALOG_TAG = "Date Dialog";
	static final String TIME_DIALOG_TAG = "Time Dialog";
	public static final int DEFAULT_HOUR = 15;
	public static final int DEFAULT_MINUTES = 30;
	
	public DialogFragment dialog;
	private MainActivity mActivity;
	
	
    
	@Override
	public void onCreate(Bundle savedInstanceState) {
	  super.onCreate(savedInstanceState);
	  mActivity = (MainActivity)getActivity();
	  currentDate = mActivity.getChosenDate();
	  Log.v(TAG, "Created.");
	  
	}
	
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
	// Inflate the layout for this fragment
	View v = inflater.inflate(R.layout.addevent, container, false);
	 
    viewDate = (TextView) v.findViewById(R.id.viewDate);
    viewTime = (TextView) v.findViewById(R.id.viewTime);
    changeDate = (ImageButton) v.findViewById(R.id.changeDate);
    changeTime = (ImageButton) v.findViewById(R.id.changeTime);
    messageText = (EditText) v.findViewById(R.id.messageText);
    save = (Button) v.findViewById(R.id.save);
    
    dbControl = new DatabaseControl(mActivity);
    
    changeDate.setOnClickListener(this);
    changeTime.setOnClickListener(this);
    save.setOnClickListener(this);
     
    getCurrentDate();
    getCurrentTime();
	return v;		
	}
    
    
    void getCurrentDate()
    {
    	day = currentDate.get(Calendar.DATE);
        month = currentDate.get(Calendar.MONTH);
        thisYear = currentDate.get(Calendar.YEAR);
        currentDateString = Integer.toString(day) + "/" + Integer.toString(month+1) + "/" + Integer.toString(thisYear);
        viewDate.setText(currentDateString);
    }
    
    void getCurrentTime()
    {
    	hour = DEFAULT_HOUR;
        minutes = DEFAULT_MINUTES;
        
        currentTimeString = hour + ":" + minutes;
        viewTime.setText(currentTimeString);
    }

	public void onClick(View v) 
	{
		FragmentTransaction ft = getFragmentManager().beginTransaction();
		if(v == changeDate)
		{
		    dialog = new DatePickerDialogFragment(this);
		    dialog.show(ft, "date");
		}
		if(v== changeTime)
		{
			dialog = new TimePickerDialogFragment(this);
		    dialog.show(ft, "time");
		}
		if(v == save)
		{
			message = messageText.getText();
			currentDateString = (String) viewDate.getText();
			currentTimeString = (String) viewTime.getText();
			try
			{
				if(!message.toString().equals(""))
				{
					if(mActivity.getOwnerName()==null){
						
						Log.v(TAG, "owner is null, displaying the dialog");
						DisplayOwnerFragment dio = DisplayOwnerFragment.newInstance();
						dio.show(getFragmentManager(), "dialog");
						
					} else addEvent();
					
				}
				else
				{
					Toast.makeText(mActivity, "Please enter a message!", Toast.LENGTH_LONG).show();
				}
			}
			catch(SQLiteException e)
			{
				Toast.makeText(mActivity, "SQL error", Toast.LENGTH_LONG).show();
			}
		}
	}
    
	protected Dialog onCreateDialog(String tag) 
	{	
        if(tag.equals(DATE_DIALOG_TAG)){
        	return new DatePickerDialog(mActivity,dateSetListener,thisYear, month, day);
        }else if(tag.equals(TIME_DIALOG_TAG)){
        	return new TimePickerDialog(mActivity,timeSetListener,hour,minutes,false);
        }else return null;
	}
	public void addEvent(){
		dbControl.open();
		long result = dbControl.addItem(mActivity.getOwnerName(),currentDateString, currentTimeString, message.toString());
		if(result==DatabaseControl.INSERT_ERROR) Toast.makeText(mActivity, "Couldn't add an event", Toast.LENGTH_SHORT).show();
		else Toast.makeText(mActivity, "Event Added!", Toast.LENGTH_SHORT).show();
		dbControl.close();
		mActivity.getSupportFragmentManager().popBackStack();
		mActivity.restoreMainView();
		ViewPager pager = mActivity.getPager();
		MyAdapter adapter = ((MyAdapter)pager.getAdapter());
		adapter.notifyDataSetChanged();
	}
	
	private DatePickerDialog.OnDateSetListener dateSetListener = new DatePickerDialog.OnDateSetListener() {
		
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			
				thisYear = year;
				month = monthOfYear;
				day = dayOfMonth;
				updateDate();
			
		}
	};
	
	private TimePickerDialog.OnTimeSetListener timeSetListener = new TimePickerDialog.OnTimeSetListener() {
		
		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
			
			hour = hourOfDay;
			minutes = minute;
			updateTime();
			
		}
	};
	
	void updateDate()
	{
		viewDate.setText( new StringBuilder().append(day)
				.append("/")
				.append(month + 1)
				.append("/")
				.append(thisYear)
				);
	}
	
	void updateTime()
	{
		String minuteString, hourString;
        if(minutes<10)
        	minuteString = "0"+minutes;
        else
        	minuteString = minutes+"";
        if(hour<10)
        	hourString = "0"+hour;
        else
        	hourString = hour+"";
		viewTime.setText( new StringBuilder().append(hourString)
				.append(":")
				.append(minuteString));
	}

	@Override
	public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
		thisYear = year;
		month = monthOfYear;
		day = dayOfMonth;
		updateDate();
	}

	@Override
	public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
		hour = hourOfDay;
		minutes = minute;
		updateTime();
	}

}
